package com.truckdispatching.http.controller;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import com.truckdispatching.UserManager;
import com.truckdispatching.database.NotificationSql;
import com.truckdispatching.entity.Notification;
import com.truckdispatching.http.util.TDHttpController;

/**
 * 最新推送消息
 * 
 * @author Lee
 * @date 2013-5-9
 */
public class PushHttpController extends TDHttpController {

	@Override
	public String getRequestUrl() {
		return mHostUrl + "/wap/push.do";
	}

	public void sendRequest(long lastTime) {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("lastTime", String.valueOf(lastTime));
		params.put("jsessionid", UserManager.getToken());
		sendRequest(params,false);
	}

	@Override
	public void onSuccess(String response) {
		try {
			JSONArray jsonArray = getJSONArrayFromJSON(new JSONObject(response), "data", null);
			ArrayList<Notification> ns = new ArrayList<Notification>();
			if (jsonArray != null && jsonArray.length() > 0) {
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jo = jsonArray.getJSONObject(i);
					Notification n = new Notification();
					n.time = getLongFromJSON(jo, "time", 0L);
					n.content = getStringFromJSON(jo, "content", "");
					ns.add(n);
					NotificationSql.getInstance().insert(n);
				}
			}
			callOnResponseListener(ns);
		} catch (Exception e) {
			callOnResponseErrorListener(-1, "");
		}
	}

	@Override
	public void onError(int errorCode, String errorMessage) {
		callOnResponseErrorListener(errorCode, errorMessage);
	}
}
